package carltechnology.com.mahjonggame.presenter.impl;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;

import java.util.ArrayList;
import java.util.List;

import carltechnology.com.mahjonggame.mode.IData;
import carltechnology.com.mahjonggame.mode.impl.MahjongPerGameMode;
import carltechnology.com.mahjonggame.presenter.IMahjongPerGameInputPresenter;
import carltechnology.com.mahjonggame.utils.Utils;
import carltechnology.com.mahjonggame.views.IMahjongPerGameInputView;
import carltechnology.com.mahjonggame.views.impl.MahjongPerGameInputFragment;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by WZTCM on 2016/6/16.
 */
public class MahjongPerGameInputPresenter implements IMahjongPerGameInputPresenter{
    private static final String TAG = MahjongPerGameInputPresenter.class.getSimpleName();
    private IMahjongPerGameInputView myView;
    private Subscriber<? super List<String>> subs;
    private Subscription subscription;
    //private int balance;
    private MahjongPerGameInputPresenter(final IMahjongPerGameInputView view) {
        this.myView = view;
        subscription = getSubscription();
    }

    @Override
    public void endFragment() {
        subs = null;
        subscription.unsubscribe();
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            Log.d(TAG,"beforeTextChanged");
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Log.d(TAG,"changed");

        }

        @Override
        public void afterTextChanged(Editable s) {
            Log.d(TAG,"afterTextChanged");
            getPerGameInputMode();
        }
    };

    public void addTextWatcher(EditText editText){
        editText.addTextChangedListener(textWatcher);
    }

    private synchronized void getPerGameInputMode(){
        List<String> list = new ArrayList<>();
       // System.out.println(myView.getPerson1Content());
        list.add(myView.getPerson1Content());
        //System.out.println(myView.getPerson2Content());
        list.add(myView.getPerson2Content());
        //System.out.println(myView.getPerson3Content());
        list.add(myView.getPerson3Content());
       // System.out.println(myView.getPerson4Content());
        list.add(myView.getPerson4Content());
       // System.out.println(myView.getCostContent());
        list.add(myView.getCostContent());
       // System.out.println(list.toString());
        subs.onNext(list);
    }

    public static IMahjongPerGameInputPresenter getInstance(final IMahjongPerGameInputView view){
        return new MahjongPerGameInputPresenter(view);
    }

    private Subscription getSubscription(){
        return Observable.create(new Observable.OnSubscribe<List<String>>() {
            @Override
            public void call(Subscriber<? super List<String>> subscriber) {
                subs = subscriber;
            }
        })
                .onBackpressureBuffer(Utils.CONSTANT.ONBACKBUFFER_SMALL_SIZE.getConstant())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(Schedulers.computation())
                .filter(new Func1<List<String>, Boolean>() {
                    @Override
                    public Boolean call(List<String> list) {
                        if (list.size()!=5){
                            return false;
                        }
                       // System.out.println(Thread.currentThread()+"now");
                        for (int i=0;i<5;i++){
                            if (Utils.stringIsEmpty(list.get(i))){
                                myView.sendMsgToFragment(MahjongPerGameInputFragment.PERGAME_MSG.PRICE_NOTHING);
                                return false;
                            }
                        }
                        return true;
                    }
                })
                .map(new Func1<List<String>, IData>() {
                    @Override
                    public IData call(List<String> list) {
                        int []prices = new int [4];
                        int cost;
                        for (int i=0;i<4;i++){
                            prices[i] = Integer.parseInt(list.get(i));
                        }
                        cost = Integer.parseInt(list.get(4));
                        return MahjongPerGameMode._of(prices,cost);
                    }
                })
                .filter(new Func1<IData, Boolean>() {
                    @Override
                    public Boolean call(IData data) {
                        int [] prices = data.getPrice();
                        int cost = data.getCost();
                        System.out.println("right cost:"+cost);
                        if (cost<0){
                            myView.sendMsgToFragment(MahjongPerGameInputFragment.PERGAME_MSG.COST_NOTHING);
                            return false;
                        }
                        /**
                         * 计算平衡因子
                         */
                        int balance = 0;
                        for (int i=0;i<prices.length;i++){
                            balance += prices[i];
                        }
                        balance += cost;
                       // System.out.println("balance "+balance);
                        myView.sendBalanceFactorToFragment(balance);
                        /**
                         * 平衡因子不为0，则表示其无效
                         */
                        if (balance!=0){
                            myView.sendMsgToFragment(MahjongPerGameInputFragment.PERGAME_MSG.BALANCE_UNRIHGT);
                            return false;
                        }
                        System.out.println("right");
                        return true;
                    }
                })
                .subscribe(new Action1<IData>() {
                    @Override
                    public void call(IData data) {

                    }
                });
    }


}
